<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\CrontabTaskModel;
use app\service\CrontabTaskService;
use app\service\material\MaterialCostService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class VideoVersionDailyCostWork extends BaseWork implements DailyStatWork
{
    public ?int $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('video_version_daily_cost_work');
        // 设置参数
        $this->setDescription('拉取视频版本版消耗');
        // 设置参数
        $this->addArgument('num', Argument::REQUIRED, '编号')    // 脚本编号，一共十个
            ->addArgument('type', Argument::REQUIRED, '类型  1：昨日 2：自定义时间 3:当日')
            ->addArgument('start_date', null, '开始日期 Y-m-d')
            ->addArgument('end_date', null, '结束日期 Y-m-d')
            ->addArgument('file_id', null, '文件id', 0)
            ->setHelp('php think video_version_daily_cost_work [num] [type] [start_date] [end_date] [file_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        ini_set('memory_limit', '500M');
        $num = $input->getArgument('num');
        $type = $input->getArgument('type');
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');
        $fileId = $input->getArgument('file_id');
        $this->setTag(intval($num));
        if ($type == 1) {
            $startDate = $endDate = date('Y-m-d', strtotime('-1 days'));
            // 获取凌晨的时间戳
            $time = strtotime(date('Y-m-d 00:00:00'));
            // 如果已执行，就不跑了
//            if ($this->getCrontabTaskInfo()->finish_time > $time) {
//                exit;
//            }
            // 判断前置的是否跑完了
            $lastTime = CrontabTaskModel::where('task_name', 'video_cost_work')
                ->where('finish_time', '>', $time)
                ->count();
            if (! $lastTime || $lastTime < 3) {
                exit;
            }
        } elseif ($type == 3) {
            $startDate = $endDate = date('Y-m-d');
        }
        $output->writeln('=======汇总视频版本数据开始' . date('Y-m-d H:i:s', time()) . '=======');
        $dates = createDateRange($startDate, $endDate);
        foreach ($dates as $date) {
            if ($type == 4) {
                for ($i = 0; $i < 10; ++$i) {
                    $res = MaterialCostService::cacheVideoAllVersionCost($date, (int) $i, (int) $fileId);
                    if ($res) {
                        echo $date . ':' . $i . 'Ok' . PHP_EOL;
                    }
                }
            } else {
                $res = MaterialCostService::cacheVideoAllVersionCost($date, (int) $num, (int) $fileId);
            }
        }
        if ($type == 1 && $res) {
            CrontabTaskService::setSingleTask($this);
        }
        $output->writeln('=======汇总视频版本数据结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
